var createError = require('http-errors');
var path = require('path');
var express = require('express');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
const app = express();

const mongoose = require('mongoose');
//数据库连接地址  链接到myStudent数据库
var DB_URL = 'mongodb://localhost:27017/weixin'
//数据库连接
mongoose.connect(DB_URL, { useNewUrlParser: true, useUnifiedTopology: true, 'useCreateIndex': true, useFindAndModify: false })

//连接成功终端显示消息
mongoose.connection.on('connected', function () {
  console.log('mongoose connection open to ' + DB_URL)
})
//连接失败终端显示消息
mongoose.connection.on('error', function () {
  console.log('mongoose error ')
})
//连接断开终端显示消息
mongoose.connection.on('disconnected', function () {
  console.log('mongoose disconnected')
})
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

var WebSocketServer = require('websocket').server;
var http = require('http');

var server = http.createServer(function (request, response) {
  console.log((new Date()) + ' Received request for ' + request.url);
  response.writeHead(404);
  response.end();
});
server.listen(8080, function () {
  console.log((new Date()) + ' Server is listening on port 8080');
});

wsServer = new WebSocketServer({
  httpServer: server,
  // You should not use autoAcceptConnections for production
  // applications, as it defeats all standard cross-origin protection
  // facilities built into the protocol and the browser.  You should
  // *always* verify the connection's origin and decide whether or not
  // to accept it.
  autoAcceptConnections: false
});

function originIsAllowed(origin) {
  // put logic here to detect whether the specified origin is allowed.
  return true;
}
const socketControl =require('./control/socket')
wsServer.on('request', function (request) {
  if (!originIsAllowed(request.origin)) {
    // Make sure we only accept requests from an allowed origin
    request.reject();
    console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
    return;
  }

  var connection = request.accept('echo-protocol', request.origin);
  // console.log((new Date()) + ' Connection accepted.');
  socketControl.addUser(request.resourceURL.pathname.replace('/',''),connection)
  connection.on('message', function (message) {
    if (message.type === 'utf8') {
      // console.log('Received Message: ' + message.utf8Data);
      socketControl.receiveMessage(message.utf8Data, connection)
      // connection.sendUTF(message.utf8Data);
    }
    else if (message.type === 'binary') {
      console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
      connection.sendBytes(message.binaryData);
    }
  });
  connection.on('close', function (reasonCode, description) {
    console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
    socketControl.removeUser(request.resourceURL.pathname.replace('/',''),connection)

  });
});
module.exports = app;
